from PyQt5.QtWidgets import QDialog
from PyQt5.QtCore import QMetaMethod

# 自定义信号必须要以_single结尾
class DlgMutliInstance(QDialog):
    _shown = False  # 类属性来跟踪对话框是否已显示
    _existDict = {} # { identification1:_instance1, identification2:_instance2,... }
    
    def __init__(self, parent=None):
        super().__init__(parent)

    def _setIdentification(self, identification):
        self._identification = identification
        
    @classmethod
    def show(cls, parent=None, params={}, identification=""):
        identification = f"{cls.__name__}_{identification}"
        if cls._shown and identification in cls._existDict:
            instance = cls._existDict[identification]
            instance.activateWindow()
            instance.raise_()
            instance.disconnectCustomSignals()
            return instance
        else:
            # instance = cls(parent, params)  # 创建新实例并传入parent
            instance = cls(parent)  # 创建新实例并传入parent
            instance.setParent(parent)  # 设置父窗口
            instance._setIdentification(identification)
            QDialog.show(instance)  # 直接调用QDialog的show方法
            cls._shown = True
            cls._existDict[identification] = instance
            return instance
            
    def closeEvent(self, event):
        del self.__class__._existDict[self._identification]
        self.__class__._shown = False  # 使用类名访问类属性
        event.accept()
        
    def disconnectCustomSignals(self):
        meta_object = self.metaObject()
        for i in range(meta_object.methodCount()):
            meta_method = meta_object.method(i)
            if meta_method.methodType() == QMetaMethod.Signal:
                signal_name = meta_method.name().data().decode("utf-8")  # 获取字符串类型的信号名
                is_connected = self.isSignalConnected(meta_method)
                if is_connected and signal_name.endswith("_signal"):
                    signal = getattr(self, signal_name)
                    signal.disconnect()


class DlgMutliInstanceReplace(DlgMutliInstance):

    def __init__(self, parent=None):
        super().__init__(parent)

    @classmethod
    def show(cls, parent=None, params={}, identification=""):
        identification = f"{cls.__name__}_{identification}"
        if cls._shown and identification in cls._existDict:
            instance = cls._existDict[identification]
            instance.activateWindow()
            instance.raise_()
            instance.initData(params)
            instance.disconnectCustomSignals()
            return instance
        else:
            instance = cls(parent, params)  # 创建新实例并传入parent
            instance.setParent(parent)  # 设置父窗口
            instance._setIdentification(identification)
            QDialog.show(instance)  # 直接调用QDialog的show方法
            cls._shown = True
            cls._existDict[identification] = instance
            return instance
    



        

        

        
        
    
